package com.reeygu.item.controller;

import com.reeygu.item.pojo.Goods;
import com.reeygu.item.pojo.User;
import com.reeygu.item.service.GoodsService;
import com.reeygu.item.vo.GoodsVo;
import com.reeygu.item.vo.RespBean;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;


@Slf4j
@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 跳转商品列表
     * HttpSession session, @CookieValue("userTicket") String ticket 参数被MVC参数拦截器处理成User对象
     * @param model
     * @param user 通过mvc解析后的user
     * @return
     */

    @RequestMapping("/toList")
    public String toList(Model model, User user){
        System.out.println("进入到toList");
        if(user == null) {
            return "login";
        }
        log.info("获取到用户信息{}", user.toString());
        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsService.findAllGoodsVo());
        return "goodsList";
    }

    //优化上面接口：使用redis缓存页面，虽然可以减缓服务器压力，但是相对来说会比较浪费流量
    @ResponseBody
    @RequestMapping(value = "/toList/optimize", produces = "text/html;charset=utf-8")
    public String toListOptimize(Model model, User user, HttpServletRequest request, HttpServletResponse response){
        if(user == null) {
            return "login";
        }
        //redis 存在缓存，直接从缓存获取
        String html = (String) redisTemplate.opsForValue().get("goodsList");
        if(StringUtils.isEmpty(html)) {
            return html;
        }
        log.info("获取到用户信息{}", user.toString());
        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsService.findAllGoodsVo());
        WebContext context = new WebContext(request, response, request.getServletContext(),
                request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", context);
        if(!StringUtils.isEmpty(html)) {
            redisTemplate.opsForValue().set("goodsList", html, 60, TimeUnit.SECONDS);
        }
        return html;
    }

    /**
     * 跳转商品详情页
     * @param model
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping("/toDetail/{goodsId}")
    public String toDetail(Model model, User user, @PathVariable Long goodsId){
        if(user == null) {
            return "login";
        }
        GoodsVo goods = goodsService.findGoodsVoByGoodsId(goodsId);
        log.info("用户{}请求商品详情页", user.toString());
        Date startDate = goods.getStartDate();
        Date endDate = goods.getEndDate();
        Date date = new Date();
        int secKillStatus = 0;
        int remainSeconds = ((int) ((startDate.getTime() - date.getTime()) / 1000));
        log.info("开始时间：{} 结束时间：{} 当前时间：{}", startDate, endDate, date);
        log.info("当前时间在开始之前{}，当前时间在开始之后{}", date.before(startDate), date.after(startDate));
        //秒杀进行中
        if(!date.before(startDate) && date.before(endDate)) {
            secKillStatus = 1;
            remainSeconds = 0;
        //秒杀已结束
        } else if(date.after(endDate)) {
            secKillStatus = 2;
            remainSeconds = -1;
        }
        log.info("输出值secKillStatus：{}， remainSeconds：{}", secKillStatus, remainSeconds);
        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("secKillStatus", secKillStatus);
        model.addAttribute("user", user);
        model.addAttribute("goods", goods);
        return "goodsDetail";
    }
}
